<?php

/**
 * 每日0点刷新本日期初库存
 * 执行命令： php /var/www/index.php --task=dayskustocks --sku=A301,A302
 */ 
class Task_dayskustocks extends Minion_Task
{
    protected $_options = array(
        'sku'  => '',
    );
    
    public function _execute(array $params) {
        set_time_limit (0);
        $pre_date = $sku_condition = '';
        $temp = array_map('addslashes', explode(',', trim($this->_options['sku'])));
        $skus = array_filter($temp);
        if(isset($skus[0])) {
            $sku_condition = isset($skus[1]) ? (" AND sku IN ('" . implode("','", $skus) . "')") : " AND sku='{$skus[0]}'";
        }else {
            $sql_0 = "SELECT max(date) AS date FROM sku_stocks LIMIT 1";
            $pre_date = DB::query(Database::SELECT, $sql_0)->execute('newerp')->get('date');
        }
        if(empty($pre_date)) {
            $pre_date = '0000-00-00';
        }
        $curr_date = date('Y-m-d');
        $sql = "INSERT sku_stocks (`sku`,`stock`,`amount`,`warehouseid`,`enterprise_dominant`,`supplier_id`,`date`,`create_time`)(
            SELECT
                u.sku, sum(u.qty) AS `stock`, sum(u.amount) as amount,
                u.warehouseid,u.enterprise_dominant,u.supplier_id,'{$curr_date}',NOW()
            FROM (
                SELECT `sku`,`stock` AS qty,`amount`,`warehouseid`,`enterprise_dominant`,`supplier_id`
                FROM `sku_stocks` WHERE date = '{$pre_date}' {$sku_condition}
                UNION ALL
                SELECT `sku`,`warehouse_quantity` AS qty,(`single_price`*`warehouse_quantity`) as amount,`warehouseid`,`enterprise_dominant`,`supplier_id`
                FROM `warehouseorders` WHERE warehouse_date>='{$pre_date} 00:00:00' AND warehouse_date<'{$curr_date} 00:00:00' {$sku_condition}
                UNION ALL
                SELECT `sku`, -`quantity` AS qty,-(`single_price`*`quantity`) as amount,`warehouseid`,`enterprise_dominant`,`supplier_id`
                FROM `deliveryorders` WHERE delivery_date>='{$pre_date} 00:00:00' AND delivery_date<'{$curr_date} 00:00:00' {$sku_condition}
            ) u
            GROUP BY u.enterprise_dominant,u.warehouseid,u.supplier_id,u.sku HAVING stock>0
        ) ON DUPLICATE KEY UPDATE stock = VALUES(stock), amount = VALUES(amount)";
        $insert_rows = DB::query(Database::INSERT, $sql)->execute('newerp');
        if($insert_rows === false) {
            $this->endTask('insert sku_stocks failed.', 1);
        }
        $this->endTask('insert sku_stocks ok.');
    }
        
    // 计划任务结束输出
    protected function endTask($msg, $code = 0, $data = null) {
        $code = intval($code);
        $msg = addslashes($msg);
        if(!is_null($data)) {
            $data = is_array($data) ? json_encode($data) : $data;
            $dataStr = ",\n\t\"data\": \"" . addslashes($data) . "\"";
        }
        echo "{\n\t\"code\": $code,\n\t\"info\": \"$msg\"{$dataStr}\n}\n";
        exit;
    }
}